package com.example.apple.ddhr_new.activity.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.ScaleAnimation;
import android.widget.ImageView;


import com.chad.library.adapter.base.BaseItemDraggableAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.chad.library.adapter.base.callback.ItemDragAndSwipeCallback;
import com.chad.library.adapter.base.listener.OnItemDragListener;
import com.example.apple.ddhr_new.R;
import com.example.apple.ddhr_new.utils.ImageViewUtil;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import androidx.annotation.DrawableRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.RecyclerView;

import static androidx.recyclerview.widget.ItemTouchHelper.ACTION_STATE_IDLE;

public class PictureEditView extends RecyclerView {
    private int horizontalSpace ;

    public PictureAdapter getPictureAdapter() {
        return pictureAdapter;
    }

    public void setPictureAdapter(PictureAdapter pictureAdapter) {
        this.pictureAdapter = pictureAdapter;
    }

    private   PictureAdapter pictureAdapter;
    private int verticalSpace;
    private  boolean allowEdit;
    private  int column;
    private  int maxSize;
    private  @DrawableRes  int chooseCapture;
    public PictureEditView(@NonNull Context context) {
        super(context);
    }

    public PictureEditView(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);

        TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.picture_edit);


        boolean edit = ta.getBoolean(R.styleable.picture_edit_allow_edit,false);
        allowEdit =edit;
        horizontalSpace = ta.getDimensionPixelOffset(R.styleable.picture_edit_horizontalSpace,dipToPx(context,10));
        verticalSpace = ta.getDimensionPixelOffset(R.styleable.picture_edit_verticalSpace,dipToPx(context,10));
        chooseCapture = ta.getResourceId(R.styleable.picture_edit_photo_src,R.drawable.dianjishangchuan);
        column = ta.getInteger(R.styleable.picture_edit_column,3);
        maxSize = ta.getInteger(R.styleable.picture_edit_max_size,0);
//        ItemDragAdapter  mAdapter = new ItemDragAdapter();
//
//        ItemDragAndSwipeCallback itemDragAndSwipeCallback = new ItemDragAndSwipeCallback(mAdapter);
//        ItemTouchHelper itemTouchHelper = new ItemTouchHelper(itemDragAndSwipeCallback);
//        itemTouchHelper.attachToRecyclerView(this);
//
//// 开启拖拽
//        mAdapter.enableDragItem(itemTouchHelper, R.id.iv_image, true);
//        mAdapter.setOnItemDragListener(new OnItemDragListener() {
//            @Override
//            public void onItemDragStart(ViewHolder viewHolder, int i) {
//
//            }
//
//            @Override
//            public void onItemDragMoving(ViewHolder viewHolder, int i, ViewHolder viewHolder1, int i1) {
//
//            }
//
//            @Override
//            public void onItemDragEnd(ViewHolder viewHolder, int i) {
//
//            }
//        });

   Adapter adapter =new Adapter()  {
       @NonNull
       @Override
       public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
           View view = LayoutInflater.from(context).inflate(R.layout.item_picture, parent, false);
           return  new ViewHolder(view) {

           };
       }



       @Override
       public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
           ImageView deleteImageView = holder.itemView.findViewById(R.id.iv_delete);
           ImageView imageView = holder.itemView.findViewById(R.id.iv_image);
           imageView.setOnClickListener(new OnClickListener() {
               @Override
               public void onClick(View v) {

                   if(allowEdit){
                       if(maxSize>0&&pictureAdapter.getItemCount()>=maxSize){
                           if(pictureAdapter!=null){
                               pictureAdapter.clickItem(position);
                           }
                       }else
                       {

                           if(position==getItemCount()-1){
                               if(pictureAdapter!=null){
                                   pictureAdapter.clickTakePhoto();
                               }
                           }else
                           {
                               if(pictureAdapter!=null){
                                   pictureAdapter.clickItem(position);
                               }
                           }
                       }

                   }else
                   {
                       if(pictureAdapter!=null){
                           pictureAdapter.clickItem(position);
                       }
                   }
               }
           });
           deleteImageView.setOnClickListener(new OnClickListener() {
               @Override
               public void onClick(View v) {
                   if(pictureAdapter!=null){
                       pictureAdapter.deleteItem(position);
                   }
               }
           });
           if(allowEdit){

               if(maxSize>0&&pictureAdapter.getItemCount()>=maxSize){

                   deleteImageView.setVisibility(VISIBLE);
                   if(pictureAdapter.getItemDrawable(position)!=null )
                   {
                       imageView.setImageDrawable(pictureAdapter.getItemDrawable(position));
                   }

                   if(pictureAdapter.getItemUrl(position)!=null){
                       ImageViewUtil.loadImage(pictureAdapter.getItemUrl(position),imageView,context);
                   }

               }else
               {
                   if(position==getItemCount()-1){
                       deleteImageView.setVisibility(GONE);
                       imageView.setImageResource(chooseCapture);

                   }else
                   {
                       deleteImageView.setVisibility(VISIBLE);
                       if(pictureAdapter.getItemDrawable(position)!=null )
                       {
                           imageView.setImageDrawable(pictureAdapter.getItemDrawable(position));
                       }

                       if(pictureAdapter.getItemUrl(position)!=null){
                           ImageViewUtil.loadImage(pictureAdapter.getItemUrl(position),imageView,context);
                       }

                   }

               }




           }else
           {
               deleteImageView.setVisibility(GONE);
               if(pictureAdapter.getItemDrawable(position)!=null )
               {
                   imageView.setImageDrawable(pictureAdapter.getItemDrawable(position));
               }

               if(pictureAdapter.getItemUrl(position)!=null){
                   ImageViewUtil.loadImage(pictureAdapter.getItemUrl(position),imageView,context);
               }
           }

       }

       @Override
       public int getItemCount() {
           if(null!=pictureAdapter)
               if(maxSize>0){
                   if(pictureAdapter.getItemCount()>=maxSize){
                       return pictureAdapter.getItemCount();
                   }else
                   {
                       return (pictureAdapter.getItemCount() + (allowEdit?1:0));
                   }
               }else
               {
                   return (pictureAdapter.getItemCount() + (allowEdit?1:0));
               }


           else {
               return allowEdit?1:0;
           }

       }
   };
        setAdapter(adapter);
        //直接使用GroupGridLayoutManager实现子项的Grid效果
        addItemDecoration(new SquareLayoutItemDecoration(horizontalSpace,verticalSpace,column) );
        GridLayoutManager gridLayoutManager = new GridLayoutManager(context, column);

        setLayoutManager(gridLayoutManager);

        //创建helper对象，callback监听recyclerView item 的各种状态
        ItemTouchHelper itemTouchHelper = new ItemTouchHelper(new ItemTouchHelper.Callback() {


            @Override
            public int getMovementFlags(@NonNull RecyclerView recyclerView, @NonNull ViewHolder viewHolder) {
                int dragFlags= ItemTouchHelper.UP | ItemTouchHelper.DOWN | ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT;
                //控制快速滑动的方向（一般是左右）
                int swipeFlags = ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT;
//还有两个flag 分别是 ItemTouchHelper.START 和 ItemTouchHelper.END ,原文的解释是：
//Horizontal direction. Resolved to LEFT or RIGHT depending on RecyclerView's layout direction. Used for swipe & drag control.
// 横向方向,取决于 RecyclerView 的方向，与 LinearLayoutManager 的 layoutReverse 有关（暂时没有验证）
                return makeMovementFlags(dragFlags, 0);//计算movement flag值
            }

            @Override
            public boolean onMove(@NonNull RecyclerView recyclerView, @NonNull ViewHolder viewHolder, @NonNull ViewHolder target) {
                if (recyclerView == null) return false;
                RecyclerView.Adapter adapter = recyclerView.getAdapter();
                if (adapter == null) return false;
                if (pictureAdapter.getItemCount() != 0) {
                    int from = viewHolder.getAdapterPosition();
                    endPosition = target.getAdapterPosition();//在这里我一直在刷新最后移动到的位置，以便接下来做其他操作

                    if(endPosition==pictureAdapter.getItemCount()||from==pictureAdapter.getItemCount()){
                        return false;
                    }

                    if(Math.abs(from/3-endPosition/3)>=1 ){
                        String object =   pictureAdapter.data().get(from);
                        String object1 =   pictureAdapter.data().get(endPosition);
                        pictureAdapter.data().remove(object);

                        pictureAdapter.data().add(endPosition,object);

                    }else {
                        Collections.swap(pictureAdapter.data(), from, endPosition);//数据交换位置
                    }

                    // 使用notifyItemMoved可以表现得更平滑，问题是 from ~ endPosition 间的item position 不会更新，并引发一系列角标混乱的问题，
                    //这个问题可以在后面的 onSelectedChanged()方法中解决。
                    // 在此做notifyItemMoved操作就足够了，notifyDataSetChanged() 和 notifyItemRangeChanged() 会打断 drag 操作。
                   adapter.notifyItemMoved(from, endPosition);


                }
                return true; // true 可以拖拽，false 不能。
            }

            @Override
            public void onSwiped(@NonNull ViewHolder viewHolder, int direction) {

            }
            int startPosition;
            int endPosition;
            @Override
            public void onSelectedChanged(RecyclerView.ViewHolder viewHolder, int actionState) {
                super.onSelectedChanged(viewHolder, actionState);

                if (viewHolder != null && actionState != ACTION_STATE_IDLE) {
                    // 非闲置状态下，记录下起始 position
                    startPosition = viewHolder.getAdapterPosition();
//                    ScaleAnimation scaleAnimation =   new
//                            ScaleAnimation(1f,1.2f,1f,1.2f,Animation.RELATIVE_TO_SELF,0.5f,Animation.RELATIVE_TO_SELF,0.5f);
//
//                    scaleAnimation.setDuration(250);
//
//                    viewHolder.itemView.setAnimation(scaleAnimation);         //设置动画
//                    scaleAnimation.startNow();
                }
                if(actionState == ACTION_STATE_IDLE) {
                    // 当手势抬起时刷新，endPosition 是在 onMove() 回调中记录下来的
                    RecyclerView.Adapter adapter = PictureEditView.this.getAdapter();
                    if (adapter != null) {
                        adapter.notifyDataSetChanged();
                    }
                }
            }
            @Override
            public boolean isLongPressDragEnabled() {
                return true;
            }
        });

//关联recyclerView，一个helper对象只能对应一个recyclerView
        itemTouchHelper.attachToRecyclerView(this);


    }


    public PictureEditView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    public  void reload(){


        getAdapter().notifyDataSetChanged();
    }


    public interface PictureAdapter{
        public  int  getItemCount();
        public  ArrayList<String>  data();
        public  void   deleteItem(int position);
        public  void   clickItem(int position);
        public  void   clickTakePhoto();
        public  String  getItemUrl(int position);
        public Drawable getItemDrawable(int position);
    }
    /**
     * dp转px
     *
     * @param context context
     * @param dpValue dp
     * @return px
     */
    private static int dipToPx(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }
    public static class SquareLayoutItemDecoration extends RecyclerView.ItemDecoration {
        private int horizontalSpace;
        private int itemNum;
        private int verticalSpace;
        /**
         *
         * @param
         * @param itemNum 每行item的个数
         */
        public SquareLayoutItemDecoration(int horizontalSpace,int verticalSpace, int itemNum) {

            this.horizontalSpace = horizontalSpace;
            this.itemNum = itemNum;
            this.horizontalSpace = horizontalSpace;
            this.verticalSpace =  verticalSpace;
        }

        @Override
        public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
            super.getItemOffsets(outRect, view, parent, state);
            outRect.bottom = verticalSpace;

            outRect.left = horizontalSpace/2;
            outRect.right = horizontalSpace/2;


        }
    }


    public class ItemDragAdapter extends BaseItemDraggableAdapter<String,BaseViewHolder> {
        public ItemDragAdapter(List data) {
            super(R.layout.item_picture, data);
        }
        public ItemDragAdapter() {
            super(R.layout.item_picture,new ArrayList<>());
        }

        @Override
        public int getItemCount() {
            if(null!=pictureAdapter)
                if(maxSize>0){
                    if(pictureAdapter.getItemCount()>=maxSize){
                        return pictureAdapter.getItemCount();
                    }else
                    {
                        return (pictureAdapter.getItemCount() + (allowEdit?1:0));
                    }
                }else
                {
                    return (pictureAdapter.getItemCount() + (allowEdit?1:0));
                }


            else {
                return allowEdit?1:0;
            }

        }

        @Override
        protected void convert(@NonNull BaseViewHolder helper, String item) {

        }

        @Override
        public void onBindViewHolder(BaseViewHolder holder, int position) {
            ImageView deleteImageView = holder.itemView.findViewById(R.id.iv_delete);
            ImageView imageView = holder.itemView.findViewById(R.id.iv_image);
            imageView.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {

                    if(allowEdit){
                        if(maxSize>0&&pictureAdapter.getItemCount()>=maxSize){
                            if(pictureAdapter!=null){
                                pictureAdapter.clickItem(position);
                            }
                        }else
                        {

                            if(position==getItemCount()-1){
                                if(pictureAdapter!=null){
                                    pictureAdapter.clickTakePhoto();
                                }
                            }else
                            {
                                if(pictureAdapter!=null){
                                    pictureAdapter.clickItem(position);
                                }
                            }
                        }

                    }else
                    {
                        if(pictureAdapter!=null){
                            pictureAdapter.clickItem(position);
                        }
                    }
                }
            });
            deleteImageView.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(pictureAdapter!=null){
                        pictureAdapter.deleteItem(position);
                    }
                }
            });
            if(allowEdit){

                if(maxSize>0&&pictureAdapter.getItemCount()>=maxSize){

                    deleteImageView.setVisibility(VISIBLE);
                    if(pictureAdapter.getItemDrawable(position)!=null )
                    {
                        imageView.setImageDrawable(pictureAdapter.getItemDrawable(position));
                    }

                    if(pictureAdapter.getItemUrl(position)!=null){
                        ImageViewUtil.loadImage(pictureAdapter.getItemUrl(position),imageView,mContext);
                    }

                }else
                {
                    if(position==getItemCount()-1){
                        deleteImageView.setVisibility(GONE);
                        imageView.setImageResource(chooseCapture);

                    }else
                    {
                        deleteImageView.setVisibility(VISIBLE);
                        if(pictureAdapter.getItemDrawable(position)!=null )
                        {
                            imageView.setImageDrawable(pictureAdapter.getItemDrawable(position));
                        }

                        if(pictureAdapter.getItemUrl(position)!=null){
                            ImageViewUtil.loadImage(pictureAdapter.getItemUrl(position),imageView,mContext);
                        }

                    }

                }




            }else
            {
                deleteImageView.setVisibility(GONE);
                if(pictureAdapter.getItemDrawable(position)!=null )
                {
                    imageView.setImageDrawable(pictureAdapter.getItemDrawable(position));
                }

                if(pictureAdapter.getItemUrl(position)!=null){
                    ImageViewUtil.loadImage(pictureAdapter.getItemUrl(position),imageView,mContext);
                }
            }
        }
    }

}
